package com.syq.controller;

import com.syq.pojo.SysUsers;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName: LoginController
 * @Description: TODO
 * @Create by: syq
 * @Date: 2022/7/19 11:36
 */

@Controller
public class LoginController {

    @GetMapping("/doLogin1")
    public String doLogoin(String username, String password,boolean rememberMe, Model model){

        Subject subject = SecurityUtils.getSubject();

        Md5Hash md5Hash=new Md5Hash(password,username,1024);

        UsernamePasswordToken usernamePasswordToken=new UsernamePasswordToken(username,md5Hash.toString());
//      记住我
        usernamePasswordToken.setRememberMe(rememberMe);

        try {
            subject.login(usernamePasswordToken);
//            Session session = subject.getSession();
//            SysUsers sysUsers= (SysUsers) subject.getPrincipal();
//            session.setAttribute("username",sysUsers.getUsername());
            return "redirect:index.jsp";
        } catch (AuthenticationException e) {
            model.addAttribute("erro",e.getMessage());
            return "login.jsp";
        }
    }

    @GetMapping("/logout")
    @ResponseBody
    public Map logout(){
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        Map map=new HashMap();
        map.put("code",0);
        return map;
    }
}
